<template>
  <div id="register-page" class="register-container">
    <div>
      <h1>注册 TIChat</h1>
    </div>
    <el-form
        :model="registerForm"
        :rules="registerRules"
        label-position="top"
        label-width="150px"
        hide-required-asterisk
        ref="registerFormRef"
        class="register-form"
    >
      <el-form-item class="login-link-container">
        <router-link to="/login" class="login-link">已有账号？点击登录</router-link>
      </el-form-item>

      <el-form-item label="邮箱" prop="userEmail">
        <el-input
            v-model="registerForm.userEmail"
            placeholder="请输入邮箱地址"
            :prefix-icon="User"
            class="input-field"
        />
      </el-form-item>

      <el-form-item label="密码" prop="userPassword">
        <el-input
            v-model="registerForm.userPassword"
            placeholder="请输入密码"
            show-password
            :prefix-icon="Lock"
            class="input-field"
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
            v-model="registerForm.confirmPassword"
            placeholder="请再次输入密码"
            :prefix-icon="Key"
            show-password
            class="input-field"
        />
      </el-form-item>

      <el-form-item class="verification-container">
        <el-input
            v-model="registerForm.emailCode"
            placeholder="请输入邮箱验证码"
            class="verification-input"
        />
        <span
            class="send-verification-code"
            @click="sendVerificationCode"
            :class="{ disabled: isCodeSent }"
        >
          {{ isCodeSent ? '验证码已发送' : '获取验证码' }}
        </span>
      </el-form-item>

      <el-form-item class="action-buttons">
        <el-button type="primary" @click="register" class="register-button">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { axiosInstance } from "@/axios";
import { ElMessage } from "element-plus";
import { User, Lock, Key} from "@element-plus/icons-vue";

import { useRouter } from 'vue-router';
const router = useRouter();
const registerForm = reactive({
  userEmail: '',
  userPassword: '',
  confirmPassword: '',
  emailCode: ''
});

const registerRules = {
  userEmail: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
  ],
  userPassword: [
    { required: true, message: "请输入密码", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    { validator: (rule, value, callback) => {
        if (value !== registerForm.userPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      }, trigger: "blur" }
  ],
  verificationCode: [
    { required: true, message: "请输入验证码", trigger: "blur" }
  ]
};

const registerFormRef = ref();
const isCodeSent = ref(false);
const sendVerificationCode = () => {
  if (isCodeSent.value) return;
  // 验证邮箱是否正确
  registerFormRef.value.validateField("userEmail", (valid) => {
    if (valid) {
      // 模拟发送验证码
      axiosInstance.get('/user/sendRegisterEmailCode?userEmail=' + registerForm.userEmail)
          .then((res) => {
            console.log(res.data)
            if(res.data.code==100000){
              ElMessage({
                message: res.data.message,
                type: "success",
              });
              isCodeSent.value = true;
            }else {
              ElMessage({
                message: res.data.message,
                type: "error"
              })
            }


          })
          .catch(() => {
            ElMessage({
              message: "发送验证码失败",
              type: "error",
            });
          });
    }
  });
};


const register = () => {
  const registerUser={
      userEmail:registerForm.userEmail,
      userPassword:registerForm.userPassword,
      emailCode:registerForm.emailCode
  }
  registerFormRef.value.validate((valid: boolean) => {
    if (valid) {
      axiosInstance.post('/user/register', registerUser)
          .then(response => {
            const data=response.data;
            if (data.code==100000){
              ElMessage({
                message: data.message,
                type: 'success',
              });
              router.push({ path: '/user/login', query: { userEmail: registerForm.userEmail }})
            }
            else{
              ElMessage({
                message: data.message,
                type: 'error',
              })
            }
          })
          .catch(error => {
            ElMessage({
              message: error.message,
              type: 'error'
            });
          });
      isCodeSent.value = false;
    }
  });
};
</script>

<style scoped>
.register-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  padding: 20px;
  background-color: #f0f2f5;
}

.register-form {
  width: 450px;
  max-width: 90%;
  padding: 30px;
  border-radius: 8px;
  background-color: #fff;
}

.input-field {
  width: 100%;
  height: 45px;
}

.verification-container {
  display: flex;
  align-items: center;
}

.verification-input {
  flex: 1;
  height: 45px;
}

.send-verification-code {
  margin-left: 10px;
  cursor: pointer;
  color: #409eff;
}

.send-verification-code.disabled {
  color: gray;
  cursor: not-allowed;
}

.action-buttons {
  display: flex;
  justify-content: center;
}

.register-button {
  width: 200px;
  height: 45px;
  font-size: 18px;
}
</style>
